//
//  DeclareDetailViewController.m
//  CloudMD
//
//  Created by centling on 16/3/18.
//  Copyright © 2016年 HuaZhengInfo. All rights reserved.
//

#import "DeclareDetailViewController.h"
#import "DetailGrabTableViewCell.h"
#import "DeclarationApproveNoCell.h"
#import "DeclarationApproveYesCell.h"
#import "ImageGrabTableViewCell.h"
#import "SelfDeclarationListModel.h"
#import "DeclarationDetailApproveModel.h"
#import "ImageModel.h"
#import "ImageTableViewCell.h"
#import "ShowImageViewController.h"
#import "XJAlbum.h"

@interface DeclareDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{
    
    UITableView * _tableView;
    NSMutableArray * _mainArray;
    NSMutableArray * _detailArray;
    NSMutableArray * _dataArray;
    NSMutableArray * _imageArray; //  图片数组
    SelfDeclarationListModel * _detailModel;
    NSString * _state; // 返回状态
}

@property (nonatomic, strong) NSArray *resultMainArray;
@property (nonatomic, strong) NSArray *resultApproveArray;
@property (nonatomic, assign) BOOL havePic;

@end

@implementation DeclareDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    //    [self requestData];
    //    [self requestImageData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // 导航栏左按钮
    UIButton * leftButton = [GDFactory creatUIButtonWithFrame:CGRectMake(0, 0, 10, 15) backImage:@"left_arrow" title:nil titleLableColcor:nil titleLabelFont:nil];
    [leftButton addTarget:self action:@selector(clickLeft) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [self creatTabelViewTitleView];
    
    // 初始化
    _dataArray = [NSMutableArray array];
    _detailArray = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    
//    _SYSCODE = [[NSString alloc] init];
//    _state = @"SUCCESS";
    
    // 请求列表数据
    [self requestData];
    
    // 请求图片
    [self requestImageData];
    
    // 创建UI
    [self buildTableview];
    
}


#pragma mark -- 请求详情数据
- (void)requestData{
    
    _mainArray = [NSMutableArray arrayWithObjects:@"申报业务:",@"申报类型:",@"申报描述:",@"资料:",@"申报时间:",nil];
    [_dataArray removeAllObjects];
    //    NSUserDefaults * IdUser = [NSUserDefaults standardUserDefaults];
//    _ID = [[NSUserDefaults standardUserDefaults] objectForKey:@"GUO"];
    NSArray * keyArray = @[@"GUID"];
    NSArray * valueArray = @[_GUID];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,SelfDeclarationDetail_URL];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * mutArray = [http.returnArray mutableCopy];
        self.resultMainArray = [mutArray[0] objectForKey:@"MAIN"];
        self.resultApproveArray = [mutArray[0] objectForKey:@"APPROVE"];
        for (NSDictionary * dataDict in self.resultMainArray) {
            
            _detailModel = [[SelfDeclarationListModel alloc] initWithDict:dataDict];
            [_dataArray addObject:_detailModel];
        }
        
        [_tableView reloadData];
        //        [SVProgressHUD dismiss];
    } withTag:101];
}


#pragma mark -- 请求图片数据
- (void)requestImageData{
    
    [_imageArray removeAllObjects];
    NSArray * keyValue = @[@"ID"];
    NSArray * valueValue = @[_ID];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueValue forKeys:keyValue];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,SelfDeclarationDownloadPic_URL];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        self.havePic = YES;
        for (NSDictionary * dataDict in array) {
            
            ImageModel * model = [[ImageModel alloc] initWith:dataDict];
            [_imageArray addObject:model.WSPATH];
            
        }
        NSUserDefaults * infoUser = [NSUserDefaults standardUserDefaults];
        [infoUser setObject:_imageArray forKey:@"INFO"];
        [_tableView reloadData];
    } withTag:101];
}

#pragma mark -- 创建Tableview
- (void)buildTableview{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCR_W, SCR_H-80) style:UITableViewStyleGrouped];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [_tableView addGestureRecognizer:tapGesture];
//    _tableView.rowHeight = SCR_H / 7;
//    _tableView.frame = CGRectMake(0, 0, SCR_W, SCR_H-80);
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"DeclarationApproveNoCell" bundle:nil] forCellReuseIdentifier:@"DeclarationApproveNoCellId"];
    [_tableView registerNib:[UINib nibWithNibName:@"DeclarationApproveYesCell" bundle:nil] forCellReuseIdentifier:@"DeclarationApproveYesCellId"];
//    _tableView.tableFooterView = [[UIView alloc] init];
    
    //隐藏分割线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

- (void)handleTap:(UITapGestureRecognizer *)tap {
    CGPoint tapLocation = [tap locationInView:_tableView];
    NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:tapLocation];
    if (indexPath.section == 0 && indexPath.row == 3) {
        ImageTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [tap locationInView:cell];
        for (UIView *view in cell.contentView.subviews) {
            if (CGRectContainsPoint(view.frame, pointInCell)) {
                if (_imageArray.count > 0) {
                    XJAlbum *imageShowVC = [[XJAlbum alloc] initWithImgUrlArr:_imageArray CurPage:view.tag];
                    imageShowVC.photoFrame = CGRectMake(0, 0, SCR_W, SCR_H);
                    [self.navigationController presentViewController:imageShowVC animated:YES completion:nil];
                }
            }
        }
    }
}


#pragma mark -- 创建导航栏标题
- (void)creatTabelViewTitleView{
    
    UIView * titleView = [GDFactory creatUIViewWithFrame:CGRectMake(0, 0, 80, 45) backColor:[UIColor clearColor]];
    UILabel * mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, titleView.frame.size.height)];
    mainLabel.textAlignment = NSTextAlignmentCenter;
    mainLabel.text = @"申报详情";
    mainLabel.textColor = [UIColor whiteColor];
    mainLabel.font = [UIFont systemFontOfSize:18];
    [titleView addSubview:mainLabel];
    
    self.navigationItem.titleView = titleView;
    
}

#pragma mark -- TableviewDelegate And DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return _mainArray.count;
    } else {
        return self.resultApproveArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 3) {
            NSString * ID = @"cell";
            
            ImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (cell == nil) {
                cell = [[ImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.havePic) {
                cell.imageArray = _imageArray;
            }
            return cell;
            
        }else{
            NSString * ID = @"cellId";
            DetailGrabTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (cell == nil) {
                cell = [[DetailGrabTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
                
            }
            cell.mainLabel.text = _mainArray[indexPath.row];
            if (indexPath.row == 0) {
                cell.detailLabel.text = _detailModel.BUSINESSNAME;
            }
            if (indexPath.row == 1) {
                cell.detailLabel.text = _detailModel.TYPENAME;
            }
            if (indexPath.row == 2) {
                cell.detailLabel.text = _detailModel.REMARK;
                CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
                CGSize expectSize = [cell.detailLabel sizeThatFits:maximumLabelSize];
                cell.detailLabel.frame = CGRectMake(10, CGRectGetMaxY(cell.mainLabel.frame)+10, cell.frame.size.width-20, expectSize.height);
            }
            if (indexPath.row == 4) {
                cell.detailLabel.text = _detailModel.DATE;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }
    } else {
        DeclarationDetailApproveModel *approveModel = [[DeclarationDetailApproveModel alloc] initWithDict:self.resultApproveArray[indexPath.row]];
        if ([approveModel.STATUSNAME isEqualToString:@"待审"]) {
            DeclarationApproveNoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeclarationApproveNoCellId" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = approveModel;
            return cell;
        } else {
            DeclarationApproveYesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeclarationApproveYesCellId" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = approveModel;
            CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
            CGSize expectSize = [cell.approveContentLabel sizeThatFits:maximumLabelSize];
            cell.approveContentLabel.frame = CGRectMake(10, CGRectGetMaxY(cell.approveDateLabel.frame)+40, cell.frame.size.width-20, expectSize.height);
            return cell;
        }
    }
}



//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    if (indexPath.row == 3) {
//        if (_imageArray.count > 0) {
////            ShowImageViewController * showVC = [[ShowImageViewController alloc] init];
////            showVC.imageArray = _imageArray;
////            [self.navigationController pushViewController:showVC animated:YES];
//            XJAlbum *imageShowVC = [[XJAlbum alloc] initWithImgUrlArr:_imageArray CurPage:0];
//            imageShowVC.photoFrame = CGRectMake(0, 0, SCR_W, SCR_H);
//            [self.navigationController presentViewController:imageShowVC animated:YES completion:nil];
//        }
//    }
//}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 && indexPath.row == 2) {
        UILabel *tmpLabel = [[UILabel alloc] init];
        tmpLabel.font = [UIFont systemFontOfSize:18];
        tmpLabel.numberOfLines = 0;
        tmpLabel.lineBreakMode = NSLineBreakByCharWrapping;
        tmpLabel.text = _detailModel.REMARK;
        CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
        CGSize expectSize = [tmpLabel sizeThatFits:maximumLabelSize];
        return SCR_H/9 * 0.4 + expectSize.height + 10;
    }
    if (indexPath.section == 0 && indexPath.row == 3) {
        if (_imageArray.count < 6) {
            return SCR_H / 5;
        } else {
            return SCR_H * 0.33;
        }
    }
    if (indexPath.section == 1) {
        DeclarationDetailApproveModel *approveModel = [[DeclarationDetailApproveModel alloc] initWithDict:self.resultApproveArray[indexPath.row]];
        if ([approveModel.STATUSNAME isEqualToString:@"已审"]) {
            UILabel *tmpLabel = [[UILabel alloc] init];
            tmpLabel.font = [UIFont systemFontOfSize:18];
            tmpLabel.numberOfLines = 0;
            tmpLabel.lineBreakMode = NSLineBreakByCharWrapping;
            tmpLabel.text = approveModel.CONTENT;
            CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
            CGSize expectSize = [tmpLabel sizeThatFits:maximumLabelSize];
            return expectSize.height + 122;
        }
    }
    
    return SCR_H / 9;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 40;
    } else {
        return 0.1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCR_W, 40)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)];
        label.text = @"申报审核状态:";
        label.textColor = RED;
        [view addSubview:label];
        return view;
    }
    return nil;
}


- (void)clickLeft{
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
